<template>
	<!-- template 1v1 -->
	<view class="template-1v1">
		<view class="view-container player-container" v-for="item in playerList" :key="item.streamID">
			<live-player v-if="item.src && (item.hasVideo || item.hasAudio)" class="player" :id="item.streamID"
				:data-userid="item.userID" :data-streamid="item.streamID" :data-streamtype="item.streamType"
				:src="item.src" mode="RTC" :autoplay="item.autoplay" :mute-audio="item.muteAudio"
				:mute-video="item.muteVideo" :orientation="item.orientation" :object-fit="item.objectFit"
				:background-mute="item.enableBackgroundMute" :min-cache="item.minCache" :max-cache="item.maxCache"
				:sound-mode="item.soundMode" :enable-recv-message="item.enableRecvMessage"
				:auto-pause-if-navigate="item.autoPauseIfNavigate"
				:auto-pause-if-open-native="item.autoPauseIfOpenNative" :debug="debug" @statechange="_playerStateChange"
				@fullscreenchange="_playerFullscreenChange" @netstatus="_playerNetStatus"
				@audiovolumenotify="_playerAudioVolumeNotify" />
		</view>
		<view :class="['view-container', 'pusher-container',pusherClass]">
			<live-pusher class="pusher" :url="pusher.url" :mode="pusher.mode" :autopush="pusher.autopush"
				:enable-camera="pusher.enableCamera" :enable-mic="pusher.enableMic" :muted="!pusher.enableMic"
				:enable-agc="pusher.enableAgc" :enable-ans="pusher.enableAns"
				:enable-ear-monitor="pusher.enableEarMonitor" :auto-focus="pusher.enableAutoFocus"
				:zoom="pusher.enableZoom" :min-bitrate="pusher.minBitrate" :max-bitrate="pusher.maxBitrate"
				:video-width="pusher.videoWidth" :video-height="pusher.videoHeight" :beauty="pusher.beautyLevel"
				:whiteness="pusher.whitenessLevel" :orientation="pusher.videoOrientation" :aspect="pusher.videoAspect"
				:device-position="pusher.frontCamera" :remote-mirror="pusher.enableRemoteMirror"
				:local-mirror="pusher.localMirror" :background-mute="pusher.enableBackgroundMute"
				:audio-quality="pusher.audioQuality" :audio-volume-type="pusher.audioVolumeType"
				:audio-reverb-type="pusher.audioReverbType" :waiting-image="pusher.waitingImage" :debug="debug"
				@statechange="_pusherStateChangeHandler" @netstatus="_pusherNetStatusHandler"
				@error="_pusherErrorHandler" @bgmstart="_pusherBGMStartHandler" @bgmprogress="_pusherBGMProgressHandler"
				@bgmcomplete="_pusherBGMCompleteHandler" @audiovolumenotify="_pusherAudioVolumeNotify" />
			<view class="loading" v-if="playerList.length === 0">
				<view class="loading-img">
					<image :src="getStaticImage('loading')" class="rotate-img"></image>
				</view>
				<view class="loading-text">等待接听中...</view>
			</view>
		</view>
		<image mode="aspectFill" class="bg" :src="avatar"></image>
		<view class="voice-call-waiting-box">
			<view class="user-avatar">
				<image :src="avatar">
				</image>
			</view>
			<view class="user-name">{{ userName }}</view>
		</view>
		<view class="handle-btns">
			<view class="btn-normal" @click="pusherAudioHandler">
				<image class="btn-image" :src="getStaticImage(`${pusher.enableMic ? 'audio-true' : 'audio-false'}`)">
				</image>
			</view>
			<view class="btn-normal" @click="soundModeChange">
				<image class="btn-image"
					:src="getStaticImage(`${soundMode === 'ear' ? 'speaker-false' : 'speaker-true'}`)">
				</image>
			</view>
		</view>
		<view class="bottom-btns">
			<!-- <view class="btn-normal" @click="pusherBeautyHandler">
				<image class="btn-image"
					:src="getStaticImage(`${pusher.beautyLevel === 9 ? 'beauty-true' : 'beauty-false'}`)">
				</image>
			</view> -->
			<view class="btn-hangup" @click="hangup">
				<image class="btn-image" :src="getStaticImage('hangup')"></image>
			</view>
		</view>
	</view>
</template>

<script lang="ts" setup>
	import { ref, computed } from "vue"
	import { onLoad, onUnload, onShow } from "@dcloudio/uni-app"
	import {
		genTestUserSig,
	} from "@/libs/im-debug/index.js";

	import TRTC from 'trtc-wx-sdk'; // 小程序构建npm引入
	import {
		getStaticImage,
	} from '@/libs/im-debug/common'
	import {
		useImStore,
		useVoiceCallStore,
	} from "@/store";


	let pusher = ref({})
	let playerList = ref([])
	let debug = ref('')
	let soundMode = ref('speaker')
	let avatar = ref('')
	let userName = ref('')
	let friendUserData = ref('')
	let friendUuid = ref('');
	const myTRTC = ref(null);
	let frequentCalls = ref(null)
	const page = getCurrentPages();
	let voiceCallExitRoomLook = false;
	let pusherClass = computed(() => {
		return playerList.value.length > 0 ? '' : 'fullscreen'
	})


	const imStore = useImStore();
	const voiceCallStore = useVoiceCallStore();
	onLoad((options) => {
		// 初始化 TRTC
		myTRTC.value = new TRTC(this)
		// 初始化推流
		init()
		// 绑定事件
		bindTRTCRoomEvent()
		// 进入房间
		enterRoom(options);
		uni.$on('on-voice-call-exit-room', (data : any) => {
			if (voiceCallExitRoomLook) {
				return false;
			}
			voiceCallExitRoomLook = true;
			exitRoom()
			let pages = getCurrentPages();
			console.log("data", data)
			console.log("pages", pages)
			console.log("on-voice-call-exit-room", page[page.length - 1].route)
			if (page[page.length - 1].route == 'im/video-call/video-call') {
				uni.navigateBack()
			}
		})
	})
	onShow(() => {
		voiceCallExitRoomLook = false;
		if (!voiceCallStore.isCallIng) {
			exitRoom()
			if (page[page.length - 1].route == 'im/video-call/video-call') {
				uni.navigateBack()
			}

		}
	})
	onUnload(() => {
		exitRoom()
	})
	const init = () => {
		// 创建推流实例
		pusher.value = myTRTC.value.createPusher()
	}
	// 进入房间
	const enterRoom = async (options) => {
		const {
			roomId,
			userId,
			friendId,
		} = options;
		const imStore = useImStore();
		friendUuid.value = friendId;
		let res = await imStore.getFriend(friendId);

		if (res.code == 0 && res.data.friendList) {
			avatar.value = res.data.friendList[0].profile.avatar;
			userName.value = res.data.friendList[0].profile.nick;
			friendUserData.value = res.data.friendList[0].profile
		}
		// 签名生成
		const {
			userSig
		} = genTestUserSig({
			SDKAppID: imStore.SDKAppID, // Your SDKAppID
			secretKey: imStore.secretKey, // Your secretKey
			userID: String(userId)
		})
		// 开启房间
		pusher.value = myTRTC.value.enterRoom({
			userID: userId,
			sdkAppID: imStore.SDKAppID,
			userSig,
			roomID: roomId,
			// 是否开启摄像头
			enableCamera: false,
			// 是否开启麦克风
			enableMic: true,
			// 美颜等级
			beautyLevel: 0,
		})
		myTRTC.value.getPusherInstance().start() // 开始推流（autoPush的模式下不需要）
	}

	const msToTime = (duration : any) : string => {
		var milliseconds : any = Math.floor((duration % 1000) / 100),
			seconds : any = Math.floor((duration / 1000) % 60),
			minutes : any = Math.floor((duration / (1000 * 60)));
		minutes = (minutes < 10) ? "0" + minutes : minutes;
		seconds = (seconds < 10) ? "0" + seconds : seconds;

		return minutes + ":" + seconds + "." + milliseconds;
	}

	// 关闭通话
	const hangup = () => {
		const voiceCallStore = useVoiceCallStore();
		// 区分 接通 关闭和未接通关闭
		if (playerList.value.length > 0) {
			frequentCalls.value = msToTime(new Date().getTime() - frequentCalls.value);
			let sendData = {
				data: 'voice-call',
				description: '',
				extension: JSON.stringify({
					roomId: voiceCallStore.currentCall.roomId,
					text: "通话时常 " + frequentCalls.value,
					show: 'true'
				})
			}
			imStore.sendMessage(sendData, 'custom', friendUuid.value)
		} else {
			let sendData = {
				data: 'voice-call',
				description: '',
				extension: JSON.stringify({
					roomId: voiceCallStore.currentCall.roomId,
					text: "已取消",
					show: 'true'
				})
			}
			imStore.sendMessage(sendData, 'custom', friendUuid.value)
			voiceCallStore.stopVoiceCallAudio()
			uni.$emit('on-im-portant-toast-close')
		}
		voiceCallStore.editCallStoreData({
			isCallIng: false,
		});
		exitRoom()
		if (page[page.length - 1].route == 'im/video-call/video-call') {
			uni.navigateBack()
		}
		console.log('挂断电话回退', page[page.length - 1].route)

	}
	// 退出房间
	const exitRoom = () => {
		const {
			pusher,
			playerList,
		} = myTRTC.value.exitRoom()
		pusher.value = pusher
		playerList.value = playerList
	}
	// 关闭开启语音
	const pusherAudioHandler = () => {
		setPusherAttributesHandler({
			enableMic: !pusher.value.enableMic,
		})
	}
	// 开启关闭摄像头
	const pusherCameraHandler = () => {
		setPusherAttributesHandler({
			enableCamera: !pusher.value.enableCamera,
		})
	}
	// 开启关闭美颜
	const pusherBeautyHandler = () => {
		const beautyLevel = pusher.value.beautyLevel === 0 ? 9 : 0
		setPusherAttributesHandler({
			beautyLevel,
		})
	}
	const mutePlayerHandle = (key, player) => {
		setPlayerAttributesHandler(player, {
			[key]: !player[key],
		})
	}
	// 切换扬声器与听筒播放
	const soundModeChange = () => {
		if (playerList.value.length === 0) return
		const players = myTRTC.value.getPlayerList()
		let toastMessage = ''
		switch (soundMode.value) {
			case 'speaker':
				soundMode.value = 'ear'
				toastMessage = '听筒播放'
				break
			case 'ear':
				soundMode.value = 'speaker'
				toastMessage = '扬声器播放'
				break
		}
		players.value.forEach((player) => {
			setPlayerAttributesHandler(player, {
				soundMode: soundMode.value,
			})
		})
		uni.showToast({
			title: toastMessage,
			icon: 'none',
		})
	}
	// 切换前置、后置摄像头
	const pusherSwitchCamera = () => {
		const frontCamera = pusher.value.frontCamera === 'front' ? 'back' : 'front'
		myTRTC.value.getPusherInstance().switchCamera(frontCamera)
	}
	// 设置 pusher 属性
	const setPusherAttributesHandler = (options) => {
		pusher.value = myTRTC.value.setPusherAttributes(options)
	}

	// 设置某个 player 属性
	const setPlayerAttributesHandler = (player, options) => {
		playerList.value = myTRTC.value.setPlayerAttributes(player.streamID, options)
	}
	// 事件监听
	const bindTRTCRoomEvent = () => {
		const TRTC_EVENT = myTRTC.value.EVENT // 初始化事件订阅
		// 对方加入
		myTRTC.value.on(TRTC_EVENT.REMOTE_USER_JOIN, (event) => {
			const {
				playerList,
			} = event.data
			playerList.value = playerList;

			frequentCalls.value = new Date().getTime();
			// 对方加入 无需发送信息
			const voiceCallStore = useVoiceCallStore();
			voiceCallStore.stopVoiceCallAudio()
		})
		// 对方挂断
		myTRTC.value.on(TRTC_EVENT.REMOTE_USER_LEAVE, (event) => {

		})

		myTRTC.value.on(TRTC_EVENT.LOCAL_JOIN, (event) => {
			// console.log('* room LOCAL_JOIN', event) // // 进房成功，触发该事件后可以对本地视频和音频进行设置
			// setPusherAttributesHandler({
			// 	enableCamera: true,
			// })
			setPusherAttributesHandler({
				enableMic: true,
			})
		})
		myTRTC.value.on(TRTC_EVENT.LOCAL_LEAVE, (event) => {
			// console.log('* room LOCAL_LEAVE', event)
		})

		// 
		// 

		myTRTC.value.on(TRTC_EVENT.ERROR, (event) => {
			// console.log('* room ERROR', event)
		})
		// 远端用户退出
		myTRTC.value.on(TRTC_EVENT.REMOTE_USER_LEAVE, (event) => {
			// console.log('* room REMOTE_USER_LEAVE', event)
			const {
				playerList,
			} = event.data
			playerList.value = playerList
		})
		// 远端用户推送视频
		myTRTC.value.on(TRTC_EVENT.REMOTE_VIDEO_ADD, (event) => {
			// console.log('* room REMOTE_VIDEO_ADD', event)
			const {
				player,
			} = event.data // 开始播放远端的视频流，默认是不播放的

			setPlayerAttributesHandler(player, {
				muteVideo: false,
			})
		})
		// 远端用户取消推送视频
		myTRTC.value.on(TRTC_EVENT.REMOTE_VIDEO_REMOVE, (event) => {
			// console.log('* room REMOTE_VIDEO_REMOVE', event)
			const {
				player,
			} = event.data
			setPlayerAttributesHandler(player, {
				muteVideo: true,
			})
		}) // 远端用户推送音频

		myTRTC.value.on(TRTC_EVENT.REMOTE_AUDIO_ADD, (event) => {
			// console.log('* room REMOTE_AUDIO_ADD', event)
			const {
				player,
			} = event.data
			setPlayerAttributesHandler(player, {
				muteAudio: false,
			})
		}) // 远端用户取消推送音频

		myTRTC.value.on(TRTC_EVENT.REMOTE_AUDIO_REMOVE, (event) => {
			// console.log('* room REMOTE_AUDIO_REMOVE', event)
			const {
				player,
			} = event.data
			setPlayerAttributesHandler(player, {
				muteAudio: true,
			})
		})
	}

	// 请保持跟 wxml 中绑定的事件名称一致
	const _pusherStateChangeHandler = (event) => {
		console.log('_pusherStateChangeHandler', event)
		myTRTC.value.pusherEventHandler(event)
	}

	const _pusherNetStatusHandler = (event) => {
		console.log('_pusherNetStatusHandler', event)
		myTRTC.value.pusherNetStatusHandler(event)
	}
	const _pusherErrorHandler = (event) => {
		myTRTC.value.pusherErrorHandler(event)
	}

	const _pusherBGMStartHandler = (event) => {
		myTRTC.value.pusherBGMStartHandler(event)
	}

	const _pusherBGMProgressHandler = (event) => {
		myTRTC.value.pusherBGMProgressHandler(event)
	}

	const _pusherBGMCompleteHandler = (event) => {
		myTRTC.value.pusherBGMCompleteHandler(event)
	}

	const _pusherAudioVolumeNotify = (event) => {
		myTRTC.value.pusherAudioVolumeNotify(event)
	}

	const _playerStateChange = (event) => {
		console.log('_playerStateChange', event)
		myTRTC.value.playerEventHandler(event)
	}

	const _playerFullscreenChange = (event) => {
		myTRTC.value.playerFullscreenChange(event)
	}

	const _playerNetStatus = (event) => {
		myTRTC.value.playerNetStatus(event)
	}

	const _playerAudioVolumeNotify = (event) => {
		myTRTC.value.playerAudioVolumeNotify(event)
	}
</script>
<style lang="scss" scoped>
	@import './video-call.scss';

	.template-1v1 {
		width: 100vw;
		height: 100vh;
		top: 0;
		left: 0;

		>image {
			height: 100%;
			width: 100%;
		}

		.player {
			height: 0 !important;
		}

		.pusher {
			height: 0;
		}

		.voice-call-waiting-box {
			background: rgba(0, 0, 0, .7);
			width: 100%;
			height: 100%;
			position: absolute;
			top: 0;
			left: 0;
			z-index: 1;

			.user-avatar {
				width: 200rpx;
				height: 200rpx;
				border-radius: 50%;
				overflow: hidden;
				margin: 0 auto;
				margin-top: 200rpx;

				image {
					width: 100%;
					height: 100%;
				}
			}

			.user-name {
				font-size: 40rpx;
				color: #fff;
				text-align: center;
				margin-top: 40rpx;
			}
		}
	}
</style>